import React from 'react';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { apiInterceptors, getApplogoList, uploadAppLogo } from '@/client/api';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import { logoUrl } from '@/utils';
import { userUpdate } from '@/client/api/login';
import { ChatContext } from '@/app/chat-context';
import { cloneDeep } from 'lodash';
import { Edge } from '@antv/x6';
import { Button, Form, Input, Modal, Spin, Select, Space, message, Radio, InputNumber, Checkbox, Switch } from 'antd';
import Icon, { LoadingOutlined, PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { dataTypeEnum, DimensionMeasurementEnum, getMetricsOptionsChange } from '@/components/workbenches/hooks/type';

const nodeModal: React.FC<{
  form: any;
  open: boolean;
  onCancel: (data: Edge) => void;
  onOk: (data: Edge, index: number) => void;
  type?: 'add' | 'edit';
  columnList?:any[];
}> = ({ form, open, onCancel, onOk, type = 'add',columnList }) => {
  const { t, i18n } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [sourceOptions, setSourceOptions] = useState<any[]>([
    // { label: 'customer_index', value: 'customer_index' },
    // { label: 'customer_index2', value: 'customer_index2' },
  ]);
  const [explanatoryNoteOptions, setExplanatoryNoteOptions] = useState<any[]>([]);
  const enableCodeTableOptions = [
    { label: '否', value: false },
    { label: '启用', value: true },
  ];
  const [formData] = Form.useForm();
  const [codeTable, setCodeTable] = useState<boolean>(false);

  const isTimeDimension = !!form?.isTimeDimension;
  const [ISsTimeDimension, setISsTimeDimension] = useState(isTimeDimension);

  useEffect(() => {
    const data = {
      columnPrecision: 2,
      enableCodeTable:false,
      ...form,
    };
    if (form.metrics === DimensionMeasurementEnum.Dimension && form.dataType != dataTypeEnum.TIME) {
      setCodeTable(!!data.enableCodeTable);
    }
    formData.setFieldsValue(data);
    const metricsOptions = getMetricsOptionsChange(form.dataType);
    setExplanatoryNoteOptions(metricsOptions);
    if(columnList?.length){
      setSourceOptions(columnList.map((item:any)=>({ label: item.field, value: item.field })));
    }
  }, []);

  const onFinish = async () => {
    // if (!formData.getFieldsValue().fields?.length) {
    //   message.error(t('w_join'));
    //   return;
    // }
    const params = {
      ...formData.getFieldsValue(),
    }
    if (params.enableCodeTable && (params.codeTableName == null || params.codeTableName === '')) {
      message.error('请选择' + t('w_CodeTable'));
      return
    }
    if (form.dataType === dataTypeEnum.TIME) {
      params.isTimeDimension = ISsTimeDimension;
    }
    onOk(params, form.idx);
  };

  return (
    <Modal className='' title={form.field} width={500} open={open} onOk={onFinish} onCancel={() => onCancel(form)}>
      <Spin spinning={loading}>
        <Form form={formData} name='formData2' onFinish={onFinish} autoComplete="off">
          <Form.Item name="name" label={t('w_explanatoryNote')} rules={[{ required: true, message: 'Missing sourceData' }]}>
            <Input className='w-80 workbenches-B620E0' maxLength={30} />
          </Form.Item>
          <div className='flex items-center'>
            <Form.Item name="metrics" label={t('w_attribute')} rules={[{ required: true, message: 'join' }]}>
              <Radio.Group options={explanatoryNoteOptions} className='w-32 black workbenches-B620E0' />
            </Form.Item>
            {form.dataType === dataTypeEnum.TIME && (
              <Form.Item label=''>
                <Checkbox checked={ISsTimeDimension}
                  onChange={e => {
                    const val = e.target.checked;
                    setISsTimeDimension(val);
                  }} className='w-24 ml-2 black workbenches-B620E0'>时间维度</Checkbox>
              </Form.Item>
            )}
          </div>
          {form.metrics === DimensionMeasurementEnum.Measurement && (
            <>
              <Form.Item name="columnPrecision" label={t('w_accuracy')} rules={[{ required: true, message: 'Missing sourceData' }]}>
                <InputNumber className=' workbenches-B620E0' min={0} max={10} defaultValue={2} />
              </Form.Item>
            </>
          )}
          {form.metrics === DimensionMeasurementEnum.Dimension && form.dataType != dataTypeEnum.TIME && (
            <>
              <Form.Item name="enableCodeTable" label={t('w_EnableCodeTable')} rules={[{ required: true, message: 'join' }]}>
                <Radio.Group options={enableCodeTableOptions} className='w-80 black workbenches-B620E0' onChange={(e) => setCodeTable(!!e.target.value)} />
              </Form.Item>
              {codeTable && (
                <Form.Item name="codeTableName" label={t('w_CodeTable')} rules={[{ required: true, message: 'Missing sourceData' }]}>
                  <Select options={sourceOptions} className='w-32 ml-2 workbenches-B620E0' />
                </Form.Item>
              )}
            </>
          )}
        </Form>
      </Spin>
    </Modal>
  );
};

export default nodeModal;    